//
//  TBCWeatherViewController.m
//  待定
//
//  Created by BoyaLee on 15/11/5.
//  Copyright © 2015年 BoyaLee. All rights reserved.
//

#import "TBCWeatherViewController.h"
#import "TBCWeatherView.h"
#import "TBCWeather.h"
#import <CoreLocation/CoreLocation.h>

@interface TBCWeatherViewController () <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *locationMgr;
@property (copy, nonatomic) NSString *cityName;
@property (copy, nonatomic) NSString *provinceName;

@end

@implementation TBCWeatherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
#pragma mark -- 添加地图定位
    if ([CLLocationManager locationServicesEnabled]) {
        
        self.locationMgr = [[CLLocationManager alloc] init];
        self.locationMgr.delegate = self;
        
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            
            [self.locationMgr requestWhenInUseAuthorization];
            
        }
        
    }
    
    self.locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationMgr.distanceFilter = 10;
    [self.locationMgr startUpdatingLocation];
    
    if (self.provinceName == nil || self.cityName == nil) {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"亲，网络不太给力哟，请耐心等候。" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
        [alertC addAction:cancelAction];
        [self presentViewController:alertC animated:YES completion:nil];
        
    }
    
}

- (void)initWeatherViews {
    
    self.navigationController.navigationBar.translucent = NO;
    
    TBCWeatherView *viewWeather = [[TBCWeatherView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64)];
    viewWeather.cityName = self.cityName;
    [self.view addSubview:viewWeather];
    
}

- (void)initWeatherData {
    
#pragma mark -- base64编码，将文字编译成base64类型
    NSString * city = [NSString stringWithFormat:@"%@|%@", self.provinceName, self.cityName];
    NSData *originData = [city dataUsingEncoding:NSUTF8StringEncoding];
    NSString *encodeResult = [originData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    NSString * urlStr = [encodeResult substringToIndex:[encodeResult length] - 2];
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@"/" withString:@"%2F"];
    
    NSString * url = [NSString stringWithFormat:@"http://c.3g.163.com/nc/weather/%@%%%dD%%%dD.html", urlStr, 3, 3];
    
    if (self.provinceName != nil && self.cityName != nil) {
    
        [self afnGetData:url Key:city];
        
    }

}

- (void)afnGetData:(NSString *)url Key:(NSString *)key {
    
    NSInteger result = [TBCAppTools getInternetReachability:url];
    
    if (result >= InternetReachableWithWWAN) {
        
        [TBCAppTools getLocalDataWithURL:url TBCToolsBlock:^(id responseObject) {
            
            [[TBCWeather shareTBCWeather] getWeather:responseObject Key:key];
            
        }];
        
    }
    
}

#pragma mark -- 协议方法，获得当前位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *location = [locations lastObject];
    
#pragma mark -- 反地理编码确定位置;根据经纬度去确定地理位置
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        if (placemarks.count == 0 || error) {
            
            return;
            
        }
        
        CLPlacemark * pm = [placemarks firstObject];
        
        if ([pm locality]) {
            
#pragma mark -- 记录当前城市名
            self.cityName = [pm.locality substringToIndex:pm.locality.length - 1];
            
        }else {
            
            self.cityName = [pm.administrativeArea substringToIndex:pm.administrativeArea.length - 1];
            
        }
        
#pragma mark -- 提取省份名
        NSString *province = [pm.addressDictionary objectForKey:@"State"];
        self.provinceName = [province substringToIndex:province.length - 1];
        
        [self initWeatherViews];
        [self initWeatherData];
        
    }];
    
    [manager stopUpdatingLocation];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
